#!/usr/bin/env python
# coding=UTF-8

import json
import os
import sys

if __name__ == '__main__':
    with open("./build/flasher_args.json", 'r', encoding='utf-8') as flash_args:
        j = json.load(flash_args)
        ss = sorted(
            ((o, f) for (o, f) in j['flash_files'].items()),
            key=lambda x: int(x[0], 0),
        )
        flash_args.close()

    base_offset = 0x0
    filename = "merge.bin"
    if len(sys.argv) == 2 :
        filename = sys.argv[1]

    with open(filename, "wb") as fout:
        for offset, name in ss:
            fout.write(b"\xff" * (int(offset, 16) - base_offset))
            base_offset = int(offset, 16)
            with open('./build/' + name, "rb") as fin:
                data = fin.read()
                fout.write(data)
                base_offset += len(data)
                fin.close()
        fout.close()
        os.system("chmod 0777 %s" % (filename))